package com.crazy.boot.util;

import org.apache.shiro.crypto.hash.Md5Hash;

import java.util.Random;

/**
 * @author CrazyCat
 * @date 2021/6/9  10:25
 */
public class ShiroMD5Utils {

    /** 随机盐的位数 **/
    public static final int SALT_LENGTH = 8;
    /** hash的散列次数 **/
    public static final int HASH_LENGTH = 1024;

    /**
     * shiromd5加密
     * @param pwd 明文密码
     * @param salt 盐值
     * @return
     */
    public static String md5Str(String pwd, String salt){
        //MD5加密，随机盐，散列
        Md5Hash md5Hash = new Md5Hash(pwd, salt, HASH_LENGTH);
        //返回加密后的字符
        return md5Hash.toHex();
    }

    /**
     * 生成随机盐值
     * @return
     */
    public static String getSalt(){
        char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890!@#$%^&*()".toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < SALT_LENGTH; i++) {
            char aChar = chars[new Random().nextInt(chars.length)];
            sb.append(aChar);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        String salt = getSalt();
        String admin = md5Str("admin", salt);
        System.out.println(salt);
        System.out.println(admin);
    }
}
